(function() {

    var
    $u = juliet.using({
        func : 'juliet.core.func-0.1'
    }),
    $ = juliet.jQuery;

    /**
     * Automatically hides popup controls on mouse click outside of a popup control.
     */
    var PopupHiderClass = function() {

        /**
         * Popup control must have "hide" method and "uid" field.
         *
         * @type Object
         * @private
         */
        this._popupControl = null;

        /**
         * Popup control's JQuery selector. Uses to determine when mouse click was
         * on popup control or not.
         *
         * @type String
         * @private
         */
        this._popupSelector = null;

        /**
         * Is monitoring in progress?
         *
         * @type Boolean
         * @private
         */
        this._monitoring = false;

        // -------------------------------------------------------
        // -                        LOGIC                        -
        // -------------------------------------------------------

        /**
         * @private
         * @param {Object} e Event object
         */
        this._documentOnClickHandler = function(e) {
            if ($(e.target).closest(this._popupSelector).length == 0) {
                this._popupControl.hide(true);
            }
        };

        //
        // API
        //

        /**
         * Start monitoring popup control visibility.
         */
        this.startMonitor = function() {
            if (this._monitoring) return;

            this._monitoring = true;
            $(document).click($u('func').proxy(this._documentOnClickHandler, this));
        };

        /**
         * Stop monitoring popup control visibility.
         */
        this.stopMonitor = function() {
            if (!this._monitoring) return;

            this._monitoring = false;
            $(document).unbind('click', $u('func').proxy(this._documentOnClickHandler));
        };

        this.initialize = function(popupControl) {
            this._popupControl = popupControl;
            this._popupSelector = '.' + popupControl.uid;
        };

    };

    juliet.registerModule('juliet.ui.popup', 'PopupHider', PopupHiderClass);

})();
